/*
 * Created by Federico Pisarello - SisDev Software (c) 2012 - fpisarello@sisdevsoft.com
 */

var popForm = 'typeFoodsPop.php';
var actionForm = 'typeFoodsAction.php';

var joDataTypeFoods;
var oTable;

/** Variable of tracking the IndexPK **/
var actionPK = undefined;
var action = undefined;

function $_init()
{
	$('#btnTypeFoods').removeClass('btnMenu').addClass('btnMenuAct');
	
	var gaiSelected;
	
	$(document).ready(function() {
    	oTable = $('#dt_typeFoods').dataTable( {
					"bJQueryUI": true,
					"sPaginationType": "two_button",
					"bInfo": false,
					"bLengthChange": false,
					"bProcessing": true,
					"bServerSide": true,
					"sAjaxSource": actionForm + "?actionOfForm=search",
					"fnRowCallback": function( nRow, aData, iDisplayIndex ) {
						if ( jQuery.inArray(aData[0], gaiSelected) != -1 )
						{
					        $(nRow).addClass('row_selected');
						}
						return nRow;
					},
					"aoColumns": [
					  			null,
					  			null,
					  			null,
					  			null
					  		]

				});
    	
    	/* Click event handler */
    	$('#dt_typeFoods tbody tr').live('click', function () {
    		var aData = oTable.fnGetData(this);
    		var iId = aData[0];
    		actionPK = aData[0];
    		
    		gaiSelected =  [];
    		if ( $(this).hasClass('row_selected') ) {
	            $(this).removeClass('row_selected');
	            actionPK = undefined;
	        }
	        else {
	            oTable.$('tr.row_selected').removeClass('row_selected');
	            $(this).addClass('row_selected');
	            gaiSelected[gaiSelected.length++] = iId;
	        }
    	} );

	});
	
	$("#typeFoodsDialog").dialog({
		autoOpen:false, 
		height:320, 
		width:600, 
		dialogClass:'no-close',
		beforeClose: function() {$("#typeFoodsDialog").empty();},
		open: function() {
			$('#typeFoodsDialog').css('background','url(imagenes/bg.gif)');
			//Add Click for All Buttons in Pop Form
			$('#btnSave').click( function(e) {
				$('#typeFoodsPopForm').submit();
			});
		}
	});
	
	//Add Click for All Buttons in Search Form
	$("#btnAdd").click( function(e) {
		addProxyShow();
    });
	
	$('#btnEdit').click( function(e) {
		editProxyShow();
	});
	
	$('#btnErase').click( function(e) {
		delProxyShow();
	});
}

function $_initPop()
{
	$('#btnExit').click( function(e) {
		$('#typeFoodsDialog').dialog('close');
	});

	var idRestaurant;
	var idTypeMenuFood;
	
	$_ValidatorSetDefaults();
	$_initPopValidator();
	
	//Populate User Data	
	if(action == iConst.EDIT)
	{
		$('#typeFoodsDescription').val(joDataTypeFoods.description);
		idTypeMenuFood = joDataTypeFoods.idMenuFood;
		idRestaurant = joDataTypeFoods.idRestaurant;
	}
	
	$.ajax({ 
	    url: actionForm, 
	    type:'POST', 
	    data: 'actionOfForm=getMenuFoods', 
	    dataType: 'json', 
	    success: function(json) { 
	        $.each(json, function(i, value) {
	        	if(value.idTypeMenuFood == idTypeMenuFood)
	        		$('#cmbTypeFoods').append($('<option selected>').text(value.description).attr('value', value.idTypeMenuFood));
	        	else
	        		$('#cmbTypeFoods').append($('<option>').text(value.description).attr('value', value.idTypeMenuFood));
	        });
	    }
	});
	
	//Populate Combos
	if($('#cmbRestaurant').length > 0)
	{
		$.ajax({ 
		    url: actionForm, 
		    type:'POST', 
		    data: 'actionOfForm=getRestaurants', 
		    dataType: 'json', 
		    success: function(json) { 
		        $.each(json, function(i, value) {
		        	if(value.idRestaurant == idRestaurant)
		        		$('#cmbRestaurant').append($('<option selected>').text(value.businessName).attr('value', value.idRestaurant));
		        	else
		        		$('#cmbRestaurant').append($('<option>').text(value.businessName).attr('value', value.idRestaurant));
		        });
		    }
		});
	}
}

function addProxyShow()
{
	//Reset State of action and IndexPK
	actionPK = undefined;
	action = iConst.NEW;
	oTable.$('tr.row_selected').removeClass('row_selected');
	$('#typeFoodsDialog').load(popForm).dialog('open');
}

function editProxyShow()
{
	if(actionPK === undefined)
	{
		$_showMessage('ALERT', 'ALERTA', strMenssageSelectionUserInGrid);
		return;
	}
	
	action = iConst.EDIT;
	var paramData =  "actionOfForm=" + iConst.EDIT + "&idTypeFood=" + actionPK;
	
    $.ajax({
        type: 'POST',
        url: actionForm,
        data: paramData,
		dataType: 'json',
        success: function(jsonObj)
                            {
        						joDataTypeFoods = jsonObj;
        						//Open Pop Dialog
        						$('#typeFoodsDialog').load(popForm).dialog('open');
                            }
        });
	
return true;
}

function $_saveTypeFood(action)
{
	var paramData = 'actionOfForm=addOrEdit&' + $("#typeFoodsPopForm").serialize();
	
	if(action == iConst.EDIT)
		paramData += '&idTypeFood=' + actionPK;
	
    $.ajax({
        type: 'POST',
        url: actionForm,
        data: paramData,
		dataType: 'json',
        success: function(jsonObj){
            if(jsonObj.status === 'OK'){
				$_showMessage('OK', jsonObj.status, jsonObj.msg);
				$('#typeFoodsDialog').dialog('close');
				oTable.fnReloadAjax();
			}
			else
				$_showMessage('ERR', jsonObj.status, jsonObj.msg);
        }
    });

return true;
}

function delProxyShow()
{
	if(actionPK === undefined)
	{
		$_showMessage('ALERT', 'ALERTA', strMenssageSelectionUserInGrid);
		return;
	}
	
	action = iConst.DELETE;
	
	$("#deleteTypeFoodsDialog").dialog({
		autoOpen: false, 
		width:350,
		position: 'center',
		open: function () {
			$('#deleteTypeFoodsDialog').css('background','url(imagenes/bg.gif)');
			$('#btnConfirmDelete').click( function(e) {
				$_del();
			});
			$('#btnExitDelete').click( function(e) {
				$('#deleteTypeFoodsDialog').dialog('close')
			})
		}
	});
	$('#deleteTypeFoodsDialog').dialog('open');	
}

function $_del()
{
	var paramData = 'actionOfForm=' + action + '&idTypeFood=' + actionPK;

    $.ajax({
            type: 'POST',
            url: actionForm,
            data: paramData,
			dataType: 'json',
            success: function(jsonObj)
                                {
                                    if(jsonObj.status === 'OK'){
										$_showMessage('OK', 'OK', jsonObj.msg);
										
										//Reset State of action and IndexPK
										actionPK = undefined;
										action = iConst.NEW;
										oTable.fnReloadAjax();
									}
									else
										$_showMessage('ERR', 'ERROR', jsonObj.msg);
                                    $('#deleteTypeFoodsDialog').dialog('close');
                                }
            });

return true;
}

function $_initPopValidator()
{
	$('#typeFoodsPopForm').validate({
		submitHandler: function() {
			$_saveTypeFood(action);
		}, 		
		rules: {
			typeFoodsDescription: {required: true,minlength: 1},
			cmbTypeFoods: {required: true,minlength: 1}
		},
		messages: {
			typeFoodsDescription: {required: '',minlength: ''},
			cmbTypeFoods: {required: '',minlength: ''}
		}
	});
}